package com.lyxmaster.lib.bluetooth;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.lyxmaster.lib.R;
import com.lyxmaster.lib.util.LibComm;
import com.lyxmaster.lib.view.BackActivity;

public class BtSearchActivity extends BackActivity {

    private ProgressBar progress;
    private ListView lvResult;

    private BluetoothAdapter btAdapter;

    private List<Map<String,Object>> listResult = new ArrayList<Map<String, Object>>();
    private List<String> listMac = new ArrayList<String>();
    private SimpleAdapter spAdapter;

    private int scacCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bt_search);

        progress = (ProgressBar)this.findViewById(R.id.progress);
        lvResult = (ListView)this.findViewById(R.id.listview);

        this.setTitle("搜索蓝牙");

        onInit();
    }

    private void onInit()
    {
        spAdapter = new SimpleAdapter(this, listResult, R.layout.adapter_lv_bt, new String[]{"name", "mac"}, new int[]{R.id.tv_name, R.id.tv_mac});

        lvResult.setAdapter(spAdapter);
        lvResult.setOnItemClickListener(lvItemClick);

        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(myReceiver, filter);

        btAdapter = BluetoothAdapter.getDefaultAdapter();
        btAdapter.startDiscovery();
    }

    private AdapterView.OnItemClickListener lvItemClick = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int position,
                                long id) {
            // TODO Auto-generated method stub
            if(btAdapter != null && btAdapter.isDiscovering())
            {
                btAdapter.cancelDiscovery();
            }
//            String name = "";
//            if(listResult.get(position).get("name") != null) name = listResult.get(position).get("name").toString();
//            String mac = listResult.get(position).get("mac").toString();
//            BlueToothView.connectBt(context,name, mac,true);
            final BtMode btMode = new BtMode();
            btMode.setName(LibComm.getString(listResult.get(position).get("name")));
            btMode.setMac(LibComm.getString(listResult.get(position).get("mac")));

            BtHelper.getInstance().connectBt(context, btMode.getName(), btMode.getMac(), new BtHelper.OnConnectListener() {
                @Override
                public void onSuccess() {
                    Intent intent = new Intent();
                    intent.putExtra(BtMode.class.getName(), new Gson().toJson(btMode));
                    BtSearchActivity.this.setResult(Activity.RESULT_OK, intent);
                    BtSearchActivity.this.finish();
                }

                @Override
                public void onError(String strError) {

                }
            });
        }
    };

    private BroadcastReceiver myReceiver = new BroadcastReceiver()
    {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            if(BluetoothDevice.ACTION_FOUND.equals(intent.getAction()))
            {
                BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                int index = listMac.indexOf(btDevice.getAddress());
                Map<String, Object> map = new HashMap<String, Object>();
                if(index != -1)
                {
                    map.put("name", btDevice.getName());
                    map.put("mac", btDevice.getAddress().toUpperCase());
                    listMac.set(index, btDevice.getAddress().toUpperCase());
                    listResult.set(index, map);
                }
                else
                {
                    map.put("name", btDevice.getName());
                    map.put("mac", btDevice.getAddress().toUpperCase());
                    listMac.add(btDevice.getAddress().toUpperCase());
                    listResult.add(map);
                }

                spAdapter.notifyDataSetChanged();
            }
            else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(intent.getAction()))
            {
                if(++scacCount > 2){
                    progress.setVisibility(View.GONE);
                    scacCount = 0;
                }else{
                    btAdapter.startDiscovery();
                }
            }
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.bt_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    //当用户点击Action按钮的时候，系统会调用Activity的onOptionsItemSelected()方法
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if(id == R.id.bt_refresh){
            scacCount = 0;
            progress.setVisibility(View.VISIBLE);
            btAdapter.startDiscovery();
            return true;
        }else{
            return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        onStopBtSearch();
    }

    private void onStopBtSearch()
    {
        this.unregisterReceiver(myReceiver);
        if(this.btAdapter != null && this.btAdapter.isDiscovering())
        {
            this.btAdapter.cancelDiscovery();
        }
    }
}
